package com.tang.yuyu.util;

import com.tang.yuyu.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.util.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
@Component
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
      new HtmlParseUtil().parseJD("拿破仑").forEach(System.out::println);
    }
    public List<Content> parseJD(String keywords) throws IOException {
        //获取请求https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword="+keywords+"&enc=utf-8";
        //解析网页,(Jsoup返回Document就是Document对象)
        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");
//        System.out.println(element.html());
        ArrayList<Content> goodsList = new ArrayList<>();

        //获取所有的li元素
        Elements li = element.getElementsByTag("li");
        //h获取元素中的内容
        for (Element el : li) {
            //关于图片，很多人都是懒加载
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
//            System.out.println("==========================================");
//            System.out.println(img);
//            System.out.println(price);
//            System.out.println(title);
            Content content = new Content();
            content.setTitle(title);
            content.setImg(img);
            content.setPrice(price);
            goodsList.add(content);

        }
    return goodsList;
    }
}
